/*
 * Copyright 2023-2025 Licensed under the Dual Licensing
 * website: https://aizuda.com
 */
package com.aizuda.bpm.beetlsql.impl;

import com.aizuda.bpm.beetlsql.mapper.FlwProcessMapper;
import com.aizuda.bpm.engine.dao.FlwProcessDao;
import com.aizuda.bpm.engine.entity.FlwProcess;
import com.github.yitter.idgen.YitIdHelper;
import org.beetl.sql.core.query.Query;

import java.util.List;

/**
 * 流程定义数据访问层接口实现类
 *
 * <p>
 * <a href="https://aizuda.com">官网</a>尊重知识产权，不允许非法使用，后果自负，不允许非法使用，后果自负
 * </p>
 *
 * @author hubin
 * @since 1.0
 */
public class FlwProcessDaoImpl implements FlwProcessDao {
    private final FlwProcessMapper processMapper;

    public FlwProcessDaoImpl(FlwProcessMapper processMapper) {
        this.processMapper = processMapper;
    }

    @Override
    public boolean insert(FlwProcess process) {
        process.setId(YitIdHelper.nextId());
        return processMapper.createQuery().insertSelective(process) > 0;
    }

    @Override
    public boolean deleteById(Long id) {
        return processMapper.deleteById(id) > 0;
    }

    @Override
    public boolean updateById(FlwProcess process) {
        return processMapper.createLambdaQuery().andEq(FlwProcess::getId, process.getId()).updateSelective(process)>0;
    }

    @Override
    public boolean updateByProcessKey(FlwProcess process, String tenantId, String processKey) {
        return processMapper.createLambdaQuery().andEq(FlwProcess::getTenantId, Query.filterEmpty(tenantId))
                .andEq(FlwProcess::getProcessKey, processKey).update(process)>0;
    }

    @Override
    public FlwProcess selectById(Long id) {
        return processMapper.single(id);
    }

    @Override
    public List<FlwProcess> selectListByProcessKeyAndVersion(String tenantId, String processKey, Integer version) {
        return processMapper.createLambdaQuery().andEq(FlwProcess::getTenantId, Query.filterEmpty(tenantId))
                .andEq(FlwProcess::getProcessKey, processKey)
                .andEq(FlwProcess::getProcessVersion, Query.filterEmpty(version))
                .desc(FlwProcess::getProcessVersion).select();
    }
}
